﻿using System;
using System.Globalization;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using System.Xml;
using System.Net;
using Services;
using Utilities.Menu.UIElements;
using TrenitaliaWP7.Resources;
using Services.Menu;
using Utilities;
using System.Device.Location;
using Microsoft.Devices;
using System.IO;
using System.Xml.Serialization;
using System.Windows;


namespace TrenitaliaWP7
{
    public class MainMenu : OrientableScreen
    {

        ArrayList<MyButton> elements;

        MyButton creditsButton, settingsButton, switchButton, refreshDateTime;
        MyButton title, surtitle, fromLabel, toLabel, fromArea, toArea, dateLabel, dateArea, timeLabel, timeArea, confirmButton;
        MyButton folderButton;
        MyButton gpsStatus;
        InputManager input_manager;
        SpriteBatch spriteBatch;
        StateManager StateManager;
        public DateTime dateTime;
        //bool existsPopUp;
        SpriteFont font;//, small;
        Texture2D search, circle, WhitePixel;
        Thread researhThread;
        bool researhAborted, gpsAborted;
        string savedFrom, savedTo;
        MyButton favoritesButton;
        Texture2D favorites;
        //Texture2D emptyTexture;
        SpriteFont titleFont;
        SpriteFont smallFont;
        SpriteFont verysmallFont;
        //var box = Game.Content.Load<Texture2D>("bar_box");
        Texture2D refresh;
        Texture2D back;
        Texture2D switc;
        Texture2D credits;
        Texture2D settings;
        Texture2D confirm;
        Texture2D folder;
        ArrayList<String> favoritesStrings;
        ArrayList<String> favoritesStrings2;
        bool isWorking;
        public bool openedFavourites = false;
        System.Device.Location.CivicAddressResolver CivicAddressResolver;
        GeoCoordinateWatcher GeoCoordinateWatcher;
        public MainMenu(Game game)
            : base(game)
        {
            dateTime = DateTime.Now;
            savedTo = "";
            savedFrom = "";

        }
        public MainMenu(Game game, DateTime dateTime, string from, string to)
            : base(game)
        {
            this.dateTime = dateTime;
            this.savedFrom = from;
            this.savedTo = to;
        }
        public override void Initialize()
        {
            isWorking = false;
            spriteBatch = Game.Services.GetService(typeof(SpriteBatch)) as SpriteBatch;
            StateManager = Game.Services.GetService(typeof(AStateManager)) as StateManager;
            Game.Services.RemoveService(typeof(IInputManager));
            input_manager = new InputManager(Game);
            Game.Components.Add(input_manager);
            input_manager.OnTap += on_tap;
            elements = new ArrayList<MyButton>();

            //existsPopUp = false;
            this.Enabled = true;

            base.Initialize();

            if (savedFrom != "" && savedTo != "")
            {
                fromArea.text = savedFrom;
                toArea.text = savedTo;
            }
            else if (StateManager.OptionsState.order == 0 && StateManager.OptionsState.stations1.Count > 1)
            {
                fromArea.text = StateManager.OptionsState.stations1[0];
                toArea.text = StateManager.OptionsState.stations1[1];
            }
            else if (StateManager.OptionsState.order == 1 && StateManager.OptionsState.stations2.Count > 1)
            {
                fromArea.text = StateManager.OptionsState.stations2[0];
                toArea.text = StateManager.OptionsState.stations2[1];
            }

            favoritesStrings = new ArrayList<String>();
            favoritesStrings2 = new ArrayList<String>();
            var f = StateManager.Favorites.favorites;
            for (int i = 0; i < f.Count; i++)
            {
                favoritesStrings.Add(f[i].ToString(0));
                favoritesStrings2.Add(f[i].ToString(1));
            }

        }
        protected override void LoadContent()
        {

            //GraphicsDevice.Present();

            favorites = Game.Content.Load<Texture2D>("favs");
            font = Game.Content.Load<SpriteFont>("Fonts/SegoeWP");
            //var box = Game.Content.Load<Texture2D>("bar_box");
            circle = Game.Content.Load<Texture2D>("circle");
            search = Game.Content.Load<Texture2D>("search");
            confirm = Game.Content.Load<Texture2D>("confirm");
            WhitePixel = Game.Content.Load<Texture2D>("WhitePixel");
            folder = Game.Content.Load<Texture2D>("folder");

            titleFont = Game.Content.Load<SpriteFont>("Fonts/SegoeWP_Title");
            smallFont = Game.Content.Load<SpriteFont>("Fonts/SegoeWP_Small");
            verysmallFont = Game.Content.Load<SpriteFont>("Fonts/SegoeWP_VerySmall");
            //var box = Game.Content.Load<Texture2D>("bar_box");
            refresh = Game.Content.Load<Texture2D>("refresh");
            back = Game.Content.Load<Texture2D>("back");
            switc = Game.Content.Load<Texture2D>("switch_stations");
            credits = Game.Content.Load<Texture2D>("credits");
            settings = Game.Content.Load<Texture2D>("settings");
            CivicAddressResolver = new CivicAddressResolver();
            GeoCoordinateWatcher = new GeoCoordinateWatcher();
            base.LoadContent();
        }
        void AbortResearch()
        {
            this.Enabled = true;
            researhAborted = true;
            isWorking = false;
        }
        void AbortGPS()
        {
            this.Enabled = true;
            gpsAborted = true;
            isWorking = false;
            if (fromArea != null && fromArea.text == Strings.CurrentLocation)
                fromArea.text = "";
            if (toArea != null && toArea.text == Strings.CurrentLocation)
                toArea.text = "";
        }
        public string from
        {
            get
            {
                return fromArea == null ? "" : fromArea.text;
            }
            set
            {
                fromArea.text = value;
            }
        }
        public string to
        {
            get
            {
                return toArea == null ? "" : toArea.text;
            }
            set
            {
                toArea.text = value;
            }
        }
        public override void Update(GameTime gameTime)
        {
            if (openedFavourites)
            {
                this.Enabled = false;
                input_manager.Enabled = false;
                StateManager.OpenItemListComponent(closeFavoritesSelector, abortSelector, Strings.Favorites, favoritesStrings, favoritesStrings2, smallFont);
                openedFavourites = true;
                return;
            }
            if (StateManager.OptionsState.FirstUse && !StateManager.isTrial)
            {
                if (MessageBox.Show(Strings.GPS_Alert_Message, Strings.GPS_Alert_Title, MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    StateManager.OptionsState.AllowGPS = true;
                }
                StateManager.OptionsState.FirstUse = false;
                Storage.SaveOptionsState(StateManager.OptionsState);
            }



            input_manager.Enabled = this.Enabled;
            if (StateManager.OptionsState.AllowGPS && (int)gameTime.TotalGameTime.TotalSeconds % 30 == 0)
            {
                RefreshGPSStatus();
            }
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)// && !existsPopUp)
            {
                State.DeleteSavedState();
                if (StateManager.isTrial)
                    StateManager.OpenAdvertisementsComponent();
                else
                    Game.Exit();
            }
            base.Update(gameTime);
        }

        public override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.Black);
            if (openedFavourites)
                return;
            //if (openedFavourites)
            //{
            //    this.Enabled = false;
            //    input_manager.Enabled = false;
            //    StateManager.OpenItemListComponent(closeFavoritesSelector, abortSelector, Strings.Favorites, favoritesStrings, favoritesStrings2, font);
            //    openedFavourites = true;
            //    return;
            //}

            spriteBatch.Begin();

            creditsButton.Draw(spriteBatch);
            settingsButton.Draw(spriteBatch);

            title.Draw(spriteBatch);
            surtitle.Draw(spriteBatch);
            fromLabel.Draw(spriteBatch);
            toLabel.Draw(spriteBatch);
            fromArea.Draw(spriteBatch);
            toArea.Draw(spriteBatch);
            dateLabel.Draw(spriteBatch);
            dateArea.Draw(spriteBatch);
            timeLabel.Draw(spriteBatch);
            timeArea.Draw(spriteBatch);
            confirmButton.Draw(spriteBatch);
            switchButton.Draw(spriteBatch);
            if (gpsStatus != null && StateManager.OptionsState.AllowGPS)
                gpsStatus.Draw(spriteBatch);
            refreshDateTime.Draw(spriteBatch);
            if (favoritesButton != null)
                favoritesButton.Draw(spriteBatch);
            if (folderButton != null)
                folderButton.Draw(spriteBatch);
            spriteBatch.End();
            base.Draw(gameTime);
        }
        //void AbortRefresh()
        //{
        //    isWorking = false;
        //    this.Enabled = true;
        //    input_manager.Enabled = true;
        //    ChangeOrientation();
        //}
        void on_tap(Vector2 tap_position)
        {
            //elements[10000].Draw(null);
            if (press_wait < PRESS_INTERVAL/* || existsPopUp*/ || isWorking) return;

            if (StateManager.isTrial)
            {
                if (RectContaintsVect(Game1.trial_rectangle, tap_position))
                {
                    OpenMarket(Game1.APP_ID);
                    return;
                }
            }

            if (creditsButton.tapped_on(tap_position))
                StateManager.SelectCreditsMenu();
            else if (settingsButton.tapped_on(tap_position))
                StateManager.SelectOptionsMenu(true);
            else if (switchButton.tapped_on(tap_position))
            {
                var a = toArea.text;
                toArea.text = fromArea.text;
                fromArea.text = a;
            }
            else if (fromArea.tapped_on(tap_position))
            {
                this.Enabled = false;
                input_manager.Enabled = false;
                var fromString = fromArea.text;
                if (fromString == "")
                    fromString = Strings.InsertNewItem;
                else if ((StateManager.OptionsState.order == 0 ? StateManager.OptionsState.stations1 : StateManager.OptionsState.stations2).Contains(fromString))
                    fromString = Strings.InsertNewItem;
                //var s = Strings.InsertNewItem;
                if (StateManager.OptionsState.AllowGPS)
                    StateManager.OpenItemListComponent(closeSelectorForFrom, abortSelector, Strings.From,
                        StateManager.OptionsState.order == 0 ? StateManager.OptionsState.stations1 : StateManager.OptionsState.stations2,
                        fromString, Strings.TypeStation, Strings.From, fromString == Strings.InsertNewItem, "", Strings.CurrentLocation);
                else
                    StateManager.OpenItemListComponent(closeSelectorForFrom, abortSelector, Strings.From,
                        StateManager.OptionsState.order == 0 ? StateManager.OptionsState.stations1 : StateManager.OptionsState.stations2,
                        fromString, Strings.TypeStation, Strings.From, fromString == Strings.InsertNewItem, "");
            }
            else if (toArea.tapped_on(tap_position))
            {
                this.Enabled = false;
                input_manager.Enabled = false;
                var toString = toArea.text;
                if (toString == "")
                    toString = Strings.InsertNewItem;
                else if ((StateManager.OptionsState.order == 0 ? StateManager.OptionsState.stations1 : StateManager.OptionsState.stations2).Contains(toString))
                    toString = Strings.InsertNewItem;
                //var s = Strings.InsertNewItem;
                if (StateManager.OptionsState.AllowGPS)
                    StateManager.OpenItemListComponent(closeSelectorForTo, abortSelector, Strings.To,
                        StateManager.OptionsState.order == 0 ? StateManager.OptionsState.stations1 : StateManager.OptionsState.stations2,
                        toString, Strings.TypeStation, Strings.To, toString == Strings.InsertNewItem, "", Strings.CurrentLocation);
                else
                    StateManager.OpenItemListComponent(closeSelectorForTo, abortSelector, Strings.To,
                    StateManager.OptionsState.order == 0 ? StateManager.OptionsState.stations1 : StateManager.OptionsState.stations2,
                    toString, Strings.TypeStation, Strings.To, toString == Strings.InsertNewItem, "");
            }
            else if (timeArea.tapped_on(tap_position))
            {
                this.Enabled = false;
                input_manager.Enabled = false;
                StateManager.OpenTimeSelector(closeTimeSelector, abortSelector, new TimeSpan(dateTime.Hour, dateTime.Minute, dateTime.Second), Strings.Time);
            }
            else if (dateArea.tapped_on(tap_position))
            {
                this.Enabled = false;
                input_manager.Enabled = false;
                //StateManager.OpenDateSelector(closeDateSelector, abortSelector, new TimeSpan(dateTime.Year, dateTime.Month, dateTime.Day), Strings.Date);                
                StateManager.OpenDateSelector(closeDateSelector, abortSelector, new DateTime(dateTime.Year, dateTime.Month, dateTime.Day), Strings.Date);
            }
            else if (confirmButton.tapped_on(tap_position) && !isWorking)
            {
                //var query = Utilities.computeUrl(fromArea.text, toArea.text, dateTime.Day, dateTime.Month, dateTime.Year, dateTime.Hour, dateTime.Minute);
                //startHTMLRequest(query);
                if (StateManager.isTrial)
                {
                    var hash = Storage.CreateMD5Hash(fromArea.text + toArea.text);

                    //var string_hash = "";
                    //for (int i = 0; i < hash.Length; i++)
                    //    string_hash += hash[i] + ", ";

                    if (Storage.CheckCrack(hash))
                    {
                        //StateManager.OptionsState.isCracked = true;
                        //Storage.SaveOptionsState(StateManager.OptionsState);

                        var url = "http://fboscari.altervista.org/submit_string.php/?tab=Suggerimenti&applicazione=InformaTreni&dataora=" +
                FixDateString(DateTime.Now.ToString()) + "&stringa=cracked";
                        Utilities.getHTML(url, (s) => { Game.Exit(); }, () => { Game.Exit(); });

                        MessageBox.Show(Strings.Cracked);
                        Thread.Sleep(60000);
                        Game.Exit();
                    }
                    else
                        Storage.DeleteCrackFile();
                }
                startHTMLRequest();
            }
            else if (refreshDateTime.tapped_on(tap_position))
            {
                dateTime = DateTime.Now;
                dateArea.text = getDate();
                timeArea.text = getTime();
            }
            else if (favoritesButton != null && favoritesButton.tapped_on(tap_position))
            {
                this.Enabled = false;
                input_manager.Enabled = false;
                openedFavourites = true;
                StateManager.OpenItemListComponent(closeFavoritesSelector, abortSelector, Strings.Favorites, favoritesStrings, favoritesStrings2, verysmallFont);
                return;
            }
            else if (StateManager.OptionsState.AllowGPS && gpsStatus != null && gpsStatus.tapped_on(tap_position))
                RefreshGPSStatus();
        }
        string FixDateString(string s)
        {
            string s1 = s.Replace('/', '-').Replace(':', '-').Replace(' ', '_');
            return s1;
        }
        String GetCoordinate(double c)
        {
            var s = "" + c;
            s = s.Replace(',', '.');
            return s;
        }

        void GetCurrentLocation(string box, MyButton area)
        {

            GeoCoordinate g = GeoCoordinate.Unknown;
            bool ok = GeoCoordinateWatcher.TryStart(false, new TimeSpan(0, 0, 10));
            if (ok)
                g = GeoCoordinateWatcher.Position.Location;
            else
            {
                ErrorLocation();
                area.text = "";
                EndGPSSearch();
                return;

            }
            //g = new GeoCoordinate(41.927950, 12.426730);
            //g = new GeoCoordinate(45 + 40/60, 12+15/60);
            if (g.IsUnknown)
            {
                ErrorLocation();
                area.text = "";
                EndGPSSearch();
                return;
            }


            //StateManager.Stations.LoadStations();
            //var s = StateManager.Stations.GetNearestStations(g);
            //if (s != null && s != "")
            //{
            //    area.text = s;
            //    EndGPSSearch();
            //    RefreshGPSStatus();
            //    return;
            //}
            //else
            //{
            //    ErrorLocation();
            //    area.text = "";
            //    EndGPSSearch();
            //}


            //  http://where.yahooapis.com/geocode?q=45.66,+12.&gflags=R&appid=000
            //string s = "http://where.yahooapis.com/geocode?q=" + GetCoordinate(g.Latitude) + ",+" + GetCoordinate(g.Longitude) + "&gflags=R&appid=000";

            // http://fboscari.altervista.org/ricerca_stazione.php/?log=11.27&lat=44.48

            string s = "http://fboscari.altervista.org/ricerca_stazione.php/?log=" + GetCoordinate(g.Longitude) + "&lat=" + GetCoordinate(g.Latitude);
            s = "http://fboscari.altervista.org/ricerca_stazione.php/?log=9";
            Utilities.getHTML(s, box, GotLocationHTML, ErrorLocation);
        }
        void EndGPSSearch()
        {
            StateManager.CloseLoadingComponent(this);
            this.Enabled = true;
            input_manager.Enabled = true;
            isWorking = false;
        }
        void GotLocationHTML(string html, string dest)
        {
            if (gpsAborted)
                return;
            try
            {
                LocationParser parser = new LocationParser(html);

                if (parser.IsStringPresentFromStart("non riuscita") || !parser.IsStringPresentFromStart("!"))
                {
                    ErrorLocation();
                    return;
                }
                string l = parser.GetLocation();
                if (l == null || l == "")
                {
                    ErrorLocation();
                    return;
                }
                if (dest == "from")
                    fromArea.text = l;
                else if (dest == "to")
                    toArea.text = l;
            }
            catch (Exception e)
            {
                e.ToString();
                MessageBox.Show(Strings.ErrorGettingGPS);
            }
            EndGPSSearch();
        }
        void ErrorLocation()
        {
            if (gpsAborted)
                return;

            StateManager.Stations.LoadStations();
            var g = GeoCoordinateWatcher.Position.Location;
            if (!g.IsUnknown)
            {
                var s = StateManager.Stations.GetNearestStations(g);
                if (s != null && s != "")
                {
                    if (fromArea != null && fromArea.text == Strings.CurrentLocation)
                        fromArea.text = s;
                    if (toArea != null && toArea.text == Strings.CurrentLocation)
                        toArea.text = s;
                    EndGPSSearch();
                    RefreshGPSStatus();
                    return;
                }
            }

            StateManager.CloseLoadingComponent(this);
            //StateManager.OpenErrorPopUp(ClosePopUp, Strings.ErrorGettingGPS, "", font, confirm, circle, WhitePixel, Color.Black);
            //input_manager.Enabled = false;
            //Game.Components.Remove(input_manager);
            //existsPopUp = true;
            System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
            { StateManager.OpenNotifyPopUp(Strings.ErrorGettingGPS); });

            if (fromArea != null && fromArea.text == Strings.CurrentLocation)
                fromArea.text = "";
            if (toArea != null && toArea.text == Strings.CurrentLocation)
                toArea.text = "";
        }

        void startHTMLRequest()
        {
            //if (isWorking)
            //    return;

            isWorking = true;
            StateManager.OpenLoadingComponent(this, AbortResearch);
            researhAborted = false;


            var query = Utilities.computeUrl(fromArea.text, toArea.text, dateTime.Day, dateTime.Month, dateTime.Year, dateTime.Hour, dateTime.Minute);

            //new Thread(new ThreadStart(() =>
            //{
            //    Utilities.getHTML(query, GotHTML, ErrorGettingHTML);
            //})).Start();
            researhThread = new Thread(new ThreadStart(() =>
            {
                Utilities.getHTML(query, GotHTML, ErrorGettingHTML);
            }));
            researhThread.Start();
        }
        //void ClosePopUp()
        //{
        //    existsPopUp = false;
        //    input_manager.Enabled = true;
        //    Game.Components.Add(input_manager);
        //    press_wait = 0;
        //}
        void GotHTML(string html)
        {
            //StateManager.CloseLoadingComponent(this);
            //var html = s;

            if (researhAborted)
                return;
            //HTMLPaser parser = new HTMLPaser(html);
            StateManager.CloseLoadingComponent(this);
            try
            {
                ResultParser parser = new ResultParser(html);

                //bool condiz = parser.IsStringPresentFromStart("Stazione di partenza: </strong>nessuna stazione corrisponde ai criteri di ricerca impostati.");
                bool condiz = parser.IsStringPresentFromStart(Strings.HTML_No_To_Station_Found);
                if (condiz)
                {
                    //StateManager.CloseLoadingComponent(this);
                    //StateManager.OpenErrorPopUp(ClosePopUp, Strings.NoDepartureStation, "", font, confirm, circle, WhitePixel, Color.Black);
                    //input_manager.Enabled = false;
                    //Game.Components.Remove(input_manager);
                    //existsPopUp = true;
                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
                    { StateManager.OpenNotifyPopUp(Strings.NoDepartureStation); });
                    isWorking = false;
                    return;
                }
                //condiz = parser.IsStringPresentFromStart("Stazione di arrivo: </strong>nessuna stazione corrisponde ai criteri di ricerca impostati.");
                condiz = parser.IsStringPresentFromStart(Strings.HTML_No_To_Station_Found);
                if (condiz)
                {
                    //StateManager.CloseLoadingComponent(this);
                    //StateManager.OpenErrorPopUp(ClosePopUp, Strings.NoDestinationStation, "", font, confirm, circle, WhitePixel, Color.Black);
                    //input_manager.Enabled = false;
                    //Game.Components.Remove(input_manager);
                    //existsPopUp = true;
                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
                    { StateManager.OpenNotifyPopUp(Strings.NoDestinationStation); });
                    isWorking = false;
                    return;
                }

                //condiz = parser.IsStringPresentFromStart("Stazione di partenza: </strong>piu stazioni corrispondono ai criteri di ricerca.");
                condiz = parser.IsStringPresentFromStart(Strings.HTML_Too_Much_From_Error);
                if (condiz)
                {
                    //StateManager.CloseLoadingComponent(this);
                    var list = parser.getFroms();
                    this.Enabled = false;
                    input_manager.Enabled = false;
                    var s = fromArea.text;
                    isWorking = false;
                    StateManager.OpenItemListComponent(setNewFrom, abortSelector, Strings.ToMuchFrom, list, Strings.Retype, Strings.From, "", false, s);
                    return;
                }

                condiz = parser.IsStringPresentFromStart(Strings.HTML_Too_Much_To_Error);
                if (condiz)
                {
                    //StateManager.CloseLoadingComponent(this);
                    var list = parser.getTos();
                    this.Enabled = false;
                    input_manager.Enabled = false;
                    var s = toArea.text;
                    isWorking = false;
                    StateManager.OpenItemListComponent(setNewTo, abortSelector, Strings.ToMuchTo, list, Strings.Retype, s, Strings.To, false, s);
                    return;
                }

                StateManager.OptionsState.AddStations(fromArea.text, toArea.text);
                Storage.SaveOptionsState(StateManager.OptionsState);
                var result = parser.getResult();
                result.buyQuery = Utilities.computeBuyUrl(from, to, dateTime.Day, dateTime.Month, dateTime.Year, dateTime.Hour, dateTime.Minute);
                //for (int i = 0; i < result.solutions.Count; i++)
                //    result.solutions[i].buy_query = Utilities.computeBuyUrl(from, to, dateTime.Day, dateTime.Month, dateTime.Year, dateTime.Hour, dateTime.Minute, i + 1);
                if (result.solutions.Count != 0)
                {
                    Game.Components.Remove(input_manager);
                    StateManager.CloseLoadingComponent(this);
                    isWorking = false;
                    StateManager.OpenResultMenu(result);
                }
                else
                {
                    StateManager.CloseLoadingComponent(this);
                    //StateManager.OpenErrorPopUp(ClosePopUp, Strings.NoSolutionsFound, "", font, confirm, circle, WhitePixel, Color.Black);
                    //input_manager.Enabled = false;
                    //Game.Components.Remove(input_manager);
                    //existsPopUp = true;
                    System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
                    { StateManager.OpenNotifyPopUp(Strings.NoSolutionsFound); });
                    isWorking = false;
                    return;
                }

            }
            catch (Exception e)
            {
                e.ToString();
                MessageBox.Show(Strings.ErrorGettingData);
            }

        }

        void ErrorGettingHTML()
        {
            if (researhAborted)
                return;
            StateManager.CloseLoadingComponent(this);
            //StateManager.OpenErrorPopUp(ClosePopUp, Strings.ErrorGettingData, "", font, confirm, circle, WhitePixel, Color.Black);
            //input_manager.Enabled = false;
            //Game.Components.Remove(input_manager);
            //existsPopUp = true;
            System.Windows.Deployment.Current.Dispatcher.BeginInvoke(() =>
            { StateManager.OpenNotifyPopUp(Strings.ErrorGettingData); });
            isWorking = false;
        }
        void setNewFrom(string result)
        {
            this.Enabled = true;
            input_manager.Enabled = true;
            fromArea.text = result;
            //var query = Utilities.computeUrl(fromArea.text, toArea.text, dateTime.Day, dateTime.Month, dateTime.Year, dateTime.Hour, dateTime.Minute);
            //startHTMLRequest(query);
            startHTMLRequest();
        }
        void setNewTo(string result)
        {
            this.Enabled = true;
            input_manager.Enabled = true;
            toArea.text = result;
            //var query = Utilities.computeUrl(fromArea.text, toArea.text, dateTime.Day, dateTime.Month, dateTime.Year, dateTime.Hour, dateTime.Minute);
            //startHTMLRequest(query);
            startHTMLRequest();
        }
        void closeDateSelector(DateTime newDateTime)
        {
            this.Enabled = true;
            input_manager.Enabled = true;
            dateTime = new DateTime(newDateTime.Year, newDateTime.Month, newDateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second);

            dateArea.text = getDate();
            //dateArea.UpdateTextPos();
        }
        void closeTimeSelector(DateTime newDateTime)
        {
            this.Enabled = true;
            input_manager.Enabled = true;
            dateTime = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, newDateTime.Hour, newDateTime.Minute, newDateTime.Second);
            timeArea.text = getTime();
        }
        void closeSelectorForFrom(String result)
        {
            this.Enabled = true;
            input_manager.Enabled = true;
            fromArea.text = result;

            if (result == Strings.CurrentLocation && StateManager.OptionsState.AllowGPS)
            {
                this.Enabled = false;
                input_manager.Enabled = false;
                gpsAborted = false;
                StateManager.OpenLoadingComponent(this, AbortGPS);
                isWorking = true;
                new Thread(new ThreadStart(() =>
                    {
                        GetCurrentLocation("from", fromArea);
                    })).Start();
            }

        }
        void closeSelectorForTo(String result)
        {
            this.Enabled = true;
            input_manager.Enabled = true;
            toArea.text = result;

            if (result == Strings.CurrentLocation && StateManager.OptionsState.AllowGPS)
            {
                this.Enabled = false;
                input_manager.Enabled = false;
                gpsAborted = false;
                StateManager.OpenLoadingComponent(this, AbortGPS);
                isWorking = true;
                new Thread(new ThreadStart(() =>
                {
                    GetCurrentLocation("to", toArea);
                })).Start();
            }
        }
        void closeFavoritesSelector(String chosen)
        {
            this.Enabled = true;
            input_manager.Enabled = true;
            for (int i = 0; i < favoritesStrings.Count; i++)
                if (chosen == favoritesStrings[i] + " " + favoritesStrings2[i])
                {
                    StateManager.OpenDetailsMenu(StateManager.Favorites.favorites[i], true);
                    break;
                }
        }
        String getDate()
        {

            int a = dateTime.Day;
            var s = "" + a + " / ";
            a = dateTime.Month;
            if (a < 10)
                s = s + "0" + a;
            else
                s = s + a;
            s = s + " / " + dateTime.Year;
            return s;
        }
        String getTime()
        {
            var s = "";
            if (dateTime.Hour < 10)
                s = "0";
            s += dateTime.Hour + " : ";
            if (dateTime.Minute < 10)
                s += "0";
            s += dateTime.Minute;
            return s;
        }
        public override void SetPortraitOrientation()
        {


            surtitle = new MyButton(new Rectangle(20, 0, 200, 60), Strings.AppTitle, Color.White, font, TextPos.Left);
            title = new MyButton(new Rectangle(20, 60, 200, 80), Strings.Title, Color.White, titleFont, TextPos.Left);

            fromLabel = new MyButton(new Rectangle(20, 130, 200, 40), Strings.From, Color.White, font, TextPos.Left);
            var s = fromArea == null ? "" : fromArea.text;
            fromArea = new MyButton(new Rectangle(20, 160, 440, 60), s, Color.Black, font, TextPos.Center, WhitePixel, Color.LightGray);

            switchButton = new MyButton(new Rectangle(410, 245, 50, 50), switc, Color.White, circle, Color.White);

            gpsStatus = new MyButton(new Rectangle(380, 70, 100, 50), "GPS", Color.White, font, TextPos.Right);

            toLabel = new MyButton(new Rectangle(20, 290, 200, 40), Strings.To, Color.White, font, TextPos.Left);
            s = toArea == null ? "" : toArea.text;
            toArea = new MyButton(new Rectangle(20, 320, 440, 60), s, Color.Black, font, TextPos.Center, WhitePixel, Color.LightGray);

            dateLabel = new MyButton(new Rectangle(20, 410, 200, 40), Strings.Date, Color.White, font, TextPos.Left);

            dateArea = new MyButton(new Rectangle(20, 440, 440, 60), getDate(), Color.Black, font, TextPos.Center, WhitePixel, Color.LightGray);

            timeLabel = new MyButton(new Rectangle(20, 530, 200, 40), Strings.Time, Color.White, font, TextPos.Left);

            timeArea = new MyButton(new Rectangle(20, 560, 440, 60), getTime(), Color.Black, font, TextPos.Center, WhitePixel, Color.LightGray);

            if (StateManager.Favorites.favorites.Count == 0 && StateManager.SavedResults.Count == 0)
            {
                creditsButton = new MyButton(new Rectangle(150, 730, 50, 50), credits, Color.White, circle, Color.White);
                settingsButton = new MyButton(new Rectangle(280, 730, 50, 50), settings, Color.White, circle, Color.White);
                favoritesButton = null;
                folderButton = null;
            }
            else if (StateManager.Favorites.favorites.Count == 0 || StateManager.SavedResults.Count == 0)
            {
                creditsButton = new MyButton(new Rectangle(125, 730, 50, 50), credits, Color.White, circle, Color.White);
                settingsButton = new MyButton(new Rectangle(215, 730, 50, 50), settings, Color.White, circle, Color.White);
                favoritesButton = null;
                folderButton = null;
                if (StateManager.SavedResults.Count == 0)
                    favoritesButton = new MyButton(new Rectangle(305, 730, 50, 50), favorites, Color.White, circle, Color.White);
                else
                    folderButton = new MyButton(new Rectangle(305, 730, 50, 50), folder, Color.White, circle, Color.White);
            }
            else
            {
                creditsButton = new MyButton(new Rectangle(80, 730, 50, 50), credits, Color.White, circle, Color.White);
                settingsButton = new MyButton(new Rectangle(170, 730, 50, 50), settings, Color.White, circle, Color.White);
                favoritesButton = new MyButton(new Rectangle(260, 730, 50, 50), favorites, Color.White, circle, Color.White);
                folderButton = new MyButton(new Rectangle(350, 730, 50, 50), folder, Color.White, circle, Color.White);
            }

            confirmButton = new MyButton(new Rectangle(410, 650, 50, 50), search, Color.White, circle, Color.White);
            refreshDateTime = new MyButton(new Rectangle(20, 650, 50, 50), refresh, Color.White, circle, Color.White);
            RefreshGPSStatus();
        }


        public override void SetLandScapeOrientation()
        {
            surtitle = new MyButton(new Rectangle(100, 20, 200, 40), Strings.AppTitle, Color.White, font, TextPos.Left);
            title = new MyButton(new Rectangle(100, 60, 200, 60), Strings.Title, Color.White, titleFont, TextPos.Left);

            fromLabel = new MyButton(new Rectangle(100, 100, 200, 40), Strings.From, Color.White, font, TextPos.Left);
            var s = fromArea == null ? "" : fromArea.text;
            fromArea = new MyButton(new Rectangle(100, 130, 600, 60), s, Color.Black, font, TextPos.Center, WhitePixel, Color.LightGray);

            switchButton = new MyButton(new Rectangle(725, 195, 50, 50), switc, Color.White, circle, Color.White);

            gpsStatus = new MyButton(new Rectangle(700, 70, 100, 50), "GPS", Color.White, font, TextPos.Right);

            toLabel = new MyButton(new Rectangle(100, 230, 200, 40), Strings.To, Color.White, font, TextPos.Left);
            s = toArea == null ? "" : toArea.text;
            toArea = new MyButton(new Rectangle(100, 260, 600, 60), s, Color.Black, font, TextPos.Center, WhitePixel, Color.LightGray);

            dateLabel = new MyButton(new Rectangle(100, 350, 200, 40), Strings.Date, Color.White, font, TextPos.Left);

            dateArea = new MyButton(new Rectangle(100, 380, 300, 60), getDate(), Color.Black, font, TextPos.Center, WhitePixel, Color.LightGray);

            timeLabel = new MyButton(new Rectangle(500, 350, 200, 40), Strings.Time, Color.White, font, TextPos.Left);

            timeArea = new MyButton(new Rectangle(500, 380, 200, 60), getTime(), Color.Black, font, TextPos.Center, WhitePixel, Color.LightGray);



            if (StateManager.Favorites.favorites.Count == 0 && StateManager.SavedResults.Count == 0)
            {
                creditsButton = new MyButton(new Rectangle(25, 150, 50, 50), credits, Color.White, circle, Color.White);
                settingsButton = new MyButton(new Rectangle(25, 280, 50, 50), settings, Color.White, circle, Color.White);
                favoritesButton = null;
                folderButton = null;
            }
            else if (StateManager.Favorites.favorites.Count == 0 || StateManager.SavedResults.Count == 0)
            {
                creditsButton = new MyButton(new Rectangle(25, 125, 50, 50), credits, Color.White, circle, Color.White);
                settingsButton = new MyButton(new Rectangle(25, 215, 50, 50), settings, Color.White, circle, Color.White);
                favoritesButton = null;
                folderButton = null;
                if (StateManager.SavedResults.Count == 0)
                    favoritesButton = new MyButton(new Rectangle(25, 305, 50, 50), favorites, Color.White, circle, Color.White);
                else
                    folderButton = new MyButton(new Rectangle(25, 305, 50, 50), folder, Color.White, circle, Color.White);
            }
            else
            {
                creditsButton = new MyButton(new Rectangle(25, 80, 50, 50), credits, Color.White, circle, Color.White);
                settingsButton = new MyButton(new Rectangle(25, 170, 50, 50), settings, Color.White, circle, Color.White);
                favoritesButton = new MyButton(new Rectangle(25, 260, 50, 50), favorites, Color.White, circle, Color.White);
                folderButton = new MyButton(new Rectangle(25, 350, 50, 50), folder, Color.White, circle, Color.White);
            }
            confirmButton = new MyButton(new Rectangle(725, 385, 50, 50), search, Color.White, circle, Color.White);

            refreshDateTime = new MyButton(new Rectangle(425, 385, 50, 50), refresh, Color.White, circle, Color.White);
            RefreshGPSStatus();
        }
        void abortSelector()
        {
            this.Enabled = true;
            input_manager.Enabled = true;
            openedFavourites = false;
        }
        void RefreshGPSStatus()
        {

            if (gpsStatus == null || !StateManager.OptionsState.AllowGPS)
                return;

            if (GeoCoordinateWatcher.Status == GeoPositionStatus.Ready)
            {
                gpsStatus.textColor = Color.LightGreen;
                return;
            }
            try
            {
                new Thread(new ThreadStart(() =>
                {
                    GeoCoordinateWatcher.TryStart(false, new TimeSpan(0, 0, 0, 0, 100));
                    switch (GeoCoordinateWatcher.Status)
                    {
                        case GeoPositionStatus.Disabled:
                        case GeoPositionStatus.NoData:
                            gpsStatus.textColor = Color.Red;
                            return;
                        case GeoPositionStatus.Initializing:
                            gpsStatus.textColor = Color.Yellow;
                            return;
                        case GeoPositionStatus.Ready:
                            gpsStatus.textColor = Color.LightGreen;
                            return;
                        default:
                            gpsStatus.textColor = Color.White;
                            return;
                    }
                })).Start();

            }
            catch (Exception e)
            {
                e.ToString();
            }

        }
    }
}
